from pathlib import Path

from office import ppt
from traceback import format_exc
from ...base import ThreadBase
from tools import PPtReplace
from pandas import read_excel


class PptToPdfThread(ThreadBase):
    """
    PPT 转 PDF
    """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.save_dir = None
        self.ppt_dir = None

    def run(self):
        try:
            ppt.ppt2pdf(self.ppt_dir, self.save_dir)
        except Exception as e:
            self.error.emit(format_exc())

    def set_value(self, ppt_dir, save_dir):
        self.save_dir = save_dir
        self.ppt_dir = ppt_dir


class PptToImgThread(ThreadBase):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.data, self.output_path = None, None

    def run(self):
        try:
            for path in self.data:
                ppt.ppt2img(path['path'], self.output_path, path['merge'])
        except Exception as e:
            self.error.emit(format_exc())

    def set_value(self, data: list, output_path: str):
        self.data, self.output_path = data, output_path


class PPtReplaceThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.templatePath = None
        self.excelPath = None
        self.savePath = None
        self.data = None

    def run(self):
        excel_pd = read_excel(self.excelPath)
        try:
            for i in range(len(excel_pd)):
                orient = excel_pd.loc[i]
                ppt = PPtReplace(self.templatePath)
                dd = []
                for v in ppt.get_variable():
                    dd.append(orient[self.data[v]])
                ppt.set_value(dd)
                file = str(Path(self.savePath) / orient[self.data['保存文件名称']]) + '.pptx'
                ppt.replace_save(file)
        except Exception as e:
            self.error.emit(format_exc())

    def set_value(self, templatePath, excelPath, savePath, data):
        self.templatePath = templatePath
        self.excelPath = excelPath
        self.savePath = savePath
        self.data = data
